package com.baijia.authentication.principal;

import com.baijia.util.HttpClient;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @title AbstractWebApplicationService
 * @desc WebApplicationService实现类
 * @author caoliang
 * @date 2015年12月5日
 * @version 1.0
 */
public abstract class AbstractWebApplicationService implements WebApplicationService {
    private static final long serialVersionUID = -8361375509702955684L;

    protected static final Logger logger = LoggerFactory.getLogger(AbstractWebApplicationService.class);

    private static final Map<String, Object> EMPTY_MAP = Collections.unmodifiableMap(new HashMap<String, Object>());

    /** serviceId，一般为业务系统服务地址，如:http://i.genshuixue.com */
    private final String id;

    /** 跳转过来时附带的，用户原本要访问的地址 */
    private final String originalUrl;

    private final String artifactId;

    private Principal principal;

    private boolean loggedOutAlready = false;

    private final HttpClient httpClient;

    protected AbstractWebApplicationService(final String id, final String originalUrl, final String artifactId,
        final HttpClient httpClient) {
        this.id = id;
        this.originalUrl = originalUrl;
        this.artifactId = artifactId;
        this.httpClient = httpClient;
    }

    @Override
    public final String toString() {
        return this.id;
    }

    @Override
    public final String getId() {
        return this.id;
    }

    @Override
    public final String getArtifactId() {
        return this.artifactId;
    }

    @Override
    public final Map<String, Object> getAttributes() {
        return EMPTY_MAP;
    }

    protected static String cleanupUrl(final String url) {
        if (url == null) {
            return null;
        }

        final int jsessionPosition = url.indexOf(";jsession");
        if (jsessionPosition == -1) {
            return url;
        }

        final int questionMarkPosition = url.indexOf("?");
        if (questionMarkPosition < jsessionPosition) {
            return url.substring(0, url.indexOf(";jsession"));
        }

        return url.substring(0, jsessionPosition) + url.substring(questionMarkPosition);
    }

    public final String getOriginalUrl() {
        return this.originalUrl;
    }

    protected final HttpClient getHttpClient() {
        return this.httpClient;
    }

    @Override
    public boolean equals(final Object object) {
        if (object == null) {
            return false;
        }

        if (object instanceof Service) {
            final Service service = (Service) object;

            return getId().equals(service.getId());
        }

        return false;
    }

    @Override
    public int hashCode() {
        final int prime = 41;
        int result = 1;
        result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
        return result;
    }

    protected Principal getPrincipal() {
        return this.principal;
    }

    @Override
    public void setPrincipal(final Principal principal) {
        this.principal = principal;
    }

    private String getDecodedUrl(String encodedUrl) {
        try {
            int depth = 0;
            int maxDepth = 15;
            String decoded = URLDecoder.decode(encodedUrl, "UTF-8");
            while (!StringUtils.equals(encodedUrl, decoded) && depth++ < maxDepth) {
                encodedUrl = decoded;
                decoded = URLDecoder.decode(encodedUrl, "UTF-8");
            }
            return decoded;
        } catch (UnsupportedEncodingException e) {
            logger.error("Can't decode uri", e);
            return encodedUrl;
        }
    }

    @Override
    public boolean matches(final Service service) {
        return StringUtils.equals(getDecodedUrl(this.id), getDecodedUrl(service.getId()))
            || StringUtils.contains(getDecodedUrl(this.id), getDecodedUrl(service.getId()));
    }

    @Override
    public synchronized boolean logOutOfService(final String sessionIdentifier) {
        if (this.loggedOutAlready) {
            return true;
        }

        logger.debug("Sending logout request for: " + getId());

        final String logoutRequest = sessionIdentifier;

        this.loggedOutAlready = true;

        if (this.httpClient != null) {
            return this.httpClient.sendMessageToEndPoint(getOriginalUrl(), logoutRequest, true);
        }

        return false;
    }
}
